from django.http import HttpResponse
from django.shortcuts import render,redirect
import requests
import json

from django.template.context_processors import request
# Create your views here.



def index(request) : # 默认需要request
    return  HttpResponse("hello world")

# 利用render 返回html
#在app目录下创建templates并添加上html
def html_test01(request):
    return render(request,'html_test01.html')

def html_test02(request):
    name='随便取个名字，从views--》html传过去  用的是{{}}'
    name1='mocky'
    job=["ceo","cto","coo"]
    description={"name":"jack","sex":"male","age":"18"}
    list=[
        {"name":"jack","sex":"male","age":"18"},
        {"name":"john","sex":"male","age":"19"},
        {"name":"jane","sex":"female","age":"20"}
    ]
# 在函数中的字符串、列表 、字典在html上的展示
    return  render(request,'html_test02.html',{"name1":name1,"name":name,"job":job,'description':description,'list':list})

# 浏览器上方，它所访问的网址没变，但是网页里却新加了内容。这个，叫做Ajax技术
def news(req):
# 来源；1 字典 2 数据库  3 网络请求爬虫
# pip install requests
    url='https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=10037151069398&score=0&sortType=5&page=1&pageSize=10&isShadowSku=0&rid=0&fold=1'
    header={"User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.33'}
    res=requests.get(url,headers=header).text
# 语法：    str.replace(old, new )
    jsonreplace=res.replace('fetchJSON_comment98(','')
    jsonreplace=jsonreplace.replace(');','')
    # print(jsonreplace)
# text  和    json区别是什么？   为什么.json就报错？？
    dict=json.loads(jsonreplace)
    print(dict)
    comments=dict['comments']
    print(comments)
    return  render(req,'news.html',{'comments':comments})

# 视图函数一定要有一个形参
# 形参就是请求对象
# 视图函数要有一个返回值
# 返回值是一个HttpResponse对象
def webrequest(req):
    # req是一个对象，封装用户发过来的请求数据

    #- 获取请求方式 POST  GET
    print(req.method)  # get
    # - 获得在url上获得的值   /webrequest/?n=111&m=22256666
    print(req.GET)
    print(req.POST)

    # 1.响应 返回字符串内容
    # return  HttpResponse("我的网站")
    # 2.响应 返回html+render渲染
    # return render(req,'webreques.html')
    #3.响应 重定向
    return redirect("https://www.cnblogs.com/")

# 用户登录
def login(request):
    if request.method == "GET":
        return  render(request,'login.html')
    else:
        #如果是POST
        #获取用户提交的POST请求数据
        # print(request.POST)
        # <QueryDict: {'csrfmiddlewaretoken': ['KvWgI42OafifyVi7Hd47j6jNSihf4u3c0phs0GQcQtaXmE8eAQXEpWuB6AN40qe8'], 'user': ['aa'], 'password': ['123']}>

        usr=request.POST.get("user")
        psw=request.POST.get("password")
        print(usr,psw)
        if usr == 'root' and psw == '123':
            return  HttpResponse("登录成功")
        # else:
        # else  可以去掉 ，这里要注意这种写法
        # 密码错误 返回的依然是登录页面 传入参数 error ，提示用户密码错误
        return  render(request,"login.html",{'error':"密码错误"})

from app_test01.models import  UserInfo
# orm 测试
def orm(request):
    # 新建
    UserInfo.objects.create(name="jack",password="1",age="1")
    UserInfo.objects.create(name="john",password="2",age="2")
    # UserInfo.objects.create(name="duck",password="2")

    # 删除--筛选
    # UserInfo.objects.filter(id=1).delete()
    ## 删除--全部
    # UserInfo.objects.all().delete()

    #获取所有数据
    # list=UserInfo.objects.all()
    # print(list)
    # 相当列表 {对象，对象}
    # <QuerySet [<UserInfo: UserInfo object (14)>, <UserInfo: UserInfo object (15)>]>
    # for item in list:
    #     print(item.name,item.age)

    # 获取指定数据
    data=UserInfo.objects.filter(id=15)
    print(data)
    for item in data:
        print(item.name,item.age)

    # 更新
    UserInfo.objects.all().update(age='6666')

    return HttpResponse('successful!')

def management(request):
    list=UserInfo.objects.all()
    return render(request,'management.html',{'list':list})

def infoadd(request):
    if request.method == 'GET':
        return render(request,'infoadd.html')
    name=request.POST.get("name")
    age=request.POST.get("age")
    psw=request.POST.get("psw")
    UserInfo.objects.create(name=name,password=psw,age=age)
    # redirect 跳转到
    return redirect('/infomanagement')

def delete(request):
    uid=request.GET.get("uid")
    UserInfo.objects.filter(id=uid).delete()
    return redirect('/infomanagement')